<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form :model="queryForm" label-width="90px" inline ref="queryFormRef">
        <el-form-item label="是否启用" prop="status" class="w-20%">
          <el-select v-model="queryForm.status" clearable placeholder="请选择是否启用">
            <el-option label="上线" value="1" />
            <el-option label="下线" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item prop="field1" label="分类" class="w-20%">
          <el-cascader
            ref="cascaderRef"
            v-model="queryForm.field1"
            placeholder="请选择分类"
            :props="classificationCascaderProps"
            :options="classificationList"
            filterable
            :filter-method="sysFilterMethod"
            clearable
          />
        </el-form-item>
        <el-form-item prop="field2" label="等级" class="w-20%">
          <el-select v-model="queryForm.field2" placeholder="请选择等级">
            <el-option
              v-for="item in levelList"
              :key="item.levelCode"
              :label="item.levelName"
              :value="item.levelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery">
            <Icon class="mr-5px" icon="ep:search" v-hasPermi="['develop:keyword:search']" />
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <Icon class="mr-5px" icon="ep:refresh" v-hasPermi="['develop:keyword:search']" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="save" v-if="columnList.length > 0">保存</el-button>
        <el-button @click="handleImport"> 导入</el-button>
        <el-button @click="handleExport"> 导出</el-button>
      </el-form-item>
      <el-table v-loading="loading" :data="list" v-if="columnList.length > 0">
        <el-table-column
          v-for="(column, columnIndex) in columnList"
          :key="columnIndex"
          :label="column.name ? column.name : `字段${columnIndex + 1}`"
        >
          <template #default="scope">
            <div>
              <!-- <el-select v-if="scope.$index == 0">
                
              </el-select> -->
              <el-cascader
                v-if="column.index == '1'"
                ref="cascaderRef"
                v-model="scope.row[`field${column.index}`]"
                placeholder="请选择分类"
                :props="classificationCascaderProps"
                :options="classificationList"
                filterable
                :filter-method="sysFilterMethod"
                clearable
                @change="classificationChange($event, scope.$index)"
              />
              <el-select
                v-model="scope.row[`field${column.index}`]"
                placeholder="请选择"
                v-else-if="column.index == '2'"
              >
                <el-option
                  v-for="item in levelList"
                  :key="item.levelCode"
                  :label="item.levelName"
                  :value="item.levelCode"
                />
              </el-select>
              <div v-else-if="column.index == '3'" class="flex items-center">
                <ns-input
                  style="width: auto; margin-right: 8px"
                  :disabled="column.fillingMethod !== '选择器'"
                  v-model="scope.row[`field${column.index}`]"
                  placeholder="请输入字段名称"
                  maxlength="200"
                />
                <span v-if="convertTimeFormat(scope.row[`field${column.index}`])">固定期限</span>
                <span v-else>非固定期限</span>
              </div>
              <ns-input
                v-else
                :disabled="column.fillingMethod !== '选择器'"
                v-model="scope.row[`field${column.index}`]"
                placeholder="请输入字段名称"
                maxlength="200"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="scope">
            <el-button
              :icon="Minus"
              size="small"
              circle
              v-if="scope.$index !== 0"
              class="ml-12px"
              @click="delRow(scope.$index, scope.row)"
            />
            <el-button
              :icon="Plus"
              size="small"
              circle
              class="ml-12px"
              v-if="list.length === scope.$index + 1"
              @click="addRow(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="是否启用" width="200px">
          <template #default="scope">
            <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="text-center">请先进行字段配置</div>
      <ImportForm ref="importFormRef" @success="getList" />
    </ContentWrap>
  </div>
</template>

<script setup lang="tsx">
import { sysFilterMethod } from '@/utils/selectFilter'
import ImportForm from './components/ImportForm.vue'
import { Plus, Minus, Close } from '@element-plus/icons-vue'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import { valueConfGetByValue, valueConfCreateBatch } from '@/api/dataStandards/assuranceValue/index'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import { classificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import download from '@/utils/download'
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const message = useMessage() // 消息弹窗
const route = useRoute()
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const queryForm = ref({ status: '', field1: '', field2: '' })
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'cnName',
  value: 'id',
  children: 'children',
  emitPath: false
})
const list = ref<any>([
  {
    field1: '',
    field2: '',
    field3: '',
    field4: '',
    field5: '',
    field6: '',
    field7: '',
    field8: '',
    field9: '',
    field10: '',
    field11: '',
    field12: '',
    field13: '',
    field14: '',
    field15: '',
    field16: '',
    field17: '',
    field18: '',
    field19: '',
    field20: ''
  }
]) // 列表的数据

const addRow = (index) => {
  list.value.splice(index + 1, 0, {
    field1: '',
    field2: '',
    field3: '',
    field4: '',
    field5: '',
    field6: '',
    field7: '',
    field8: '',
    field9: '',
    field10: '',
    field11: '',
    field12: '',
    field13: '',
    field14: '',
    field15: '',
    field16: '',
    field17: '',
    field18: '',
    field19: '',
    field20: ''
  })
}
const delRow = (index, row) => {
  if (!!list.value[index].id) {
    assuranceApi.delCheck(list.value[index].field1).then((res) => {
      res && list.value.splice(index, 1)
    })
    return
  }
  list.value.splice(index, 1)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const importFormRef = ref()
const handleImport = () => {
  assuranceApi.importCheck(route.query.id).then((res) => {
    res && importFormRef.value.open()
  })
}
const handleExport = async () => {
  try {
    const isSure = await proxy.$modal.confirm('确定要导出当前内容吗？')
    if (!isSure) {
      return
    }
    const data = await assuranceApi.exportCheck(route.query.id)
    download.excel(data, '内容配置.xlsx')
  } catch (e) {
    ElMessage.error(e)
  }
}

const unitMap = new Map([
  ['年', 'year'],
  ['月', 'month'],
  ['天', 'day'],
  ['日', 'day']
])

const convertTimeFormat = (timeString) => {
  const regex = /(\d+)\s*([^0-9\s]+)/
  if (!timeString) {
    return false
  }
  const match = timeString.match(regex)
  if (match && unitMap.has(match[2])) {
    return true
  } else {
    return false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await valueConfGetByValue({
      dataStandardId: route.query.id,
      ...queryForm.value,
      status: queryForm.value.status || '2'
    })
    if (data.length > 0) {
      list.value = data.map((item) => {
        return {
          ...item,
          field2: Number(item.field2)
        }
      })
    } else {
      list.value = [
        {
          field1: '',
          field2: '',
          field3: '',
          field4: '',
          field5: '',
          field6: '',
          field7: '',
          field8: '',
          field9: '',
          field10: '',
          field11: '',
          field12: '',
          field13: '',
          field14: '',
          field15: '',
          field16: '',
          field17: '',
          field18: '',
          field19: '',
          field20: ''
        }
      ]
    }
    console.log(list.value, '23213123')
  } finally {
    loading.value = false
  }
}

const save = async () => {
  const params = list.value.map((item) => {
    return {
      ...item,
      dataStandardId: route.query.id
    }
  })
  const data = await valueConfCreateBatch(params)
  if (data) {
    message.success('操作成功')
    getList()
  }
}

const cascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})

const columnList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])
const getColumn = async () => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: route.query.id,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    columnList.value = data
  } else {
    columnList.value = []
  }
}

const cascaderRef = ref()
const classificationChange = (e, index) => {
  if (e) {
    const checkedNode = cascaderRef.value[index].getCheckedNodes()
    if (checkedNode[0].data.levelCode) {
      // form.value.handLevel = checkedNode[0].data.levelCode
      list.value[index].field2 = checkedNode[0].data.levelCode
    }
  }
}

// 获取模板下的分类树
const classificationList = ref([])
const getClassificationTree = async () => {
  const data = await classificationTree({
    standardId: route.query.id
  })
  classificationList.value = data
}

// 获取等级下拉列表
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  levelList.value = data
}

onMounted(() => {
  getColumn()
  getList()
  getClassificationTree()
  getLevelList()
})

defineExpose({
  getColumn
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }
  .el-form .el-select {
    width: 100%;
  }
  :deep(.hide-expand .cell) {
    display: none;
  }
  :deep(.el-form .el-cascader) {
    width: 100%;
  }
  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }
  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
